#include"mpthread.h"
using namespace std;
#include"contral.h"


void cli_cb(int fd,short event,void *arg)
{
	cout<<"cli_cb"<<endl;
	Pmpthread mthis = (Pmpthread)arg;
	//recv -> buff
	char buff[1024]={0};
	int len=recv(fd,buff,1023,0);
	cout<<"bufflen:"<<len<<"\nbuff:"<<buff<<endl;
	if(len<0)
	{
	 cout<<"recv error"<<endl<<endl;
	}
	//buff  ->   contral
	if(len==0)
	{
     cout<<"cli unlink"<<endl<<endl;

	 event_del(mthis->_event_map[fd]);
	 
	 mthis->_event_map.erase(fd);
	 int pth_num=mthis->_event_map.size();
	 send(mthis->_sock_1,&pth_num,4,0);
	 
	/* Json::Value val;
	val["type"]=MSG_TYPE_EXIT;
	val["name"]= ;
	 Contral con;
	 con.process(val,fd); */
	 

	 close(fd);
	  return ;
	}
	Contral con;
	con.process(buff,fd);
	  

}


void sock_1_cb(int fd,short event,void *arg)
{
	 cout<<"sock_1_cb"<<endl;
	//强转  arg
	Pmpthread mthis = (Pmpthread)arg;

	//recv   ->cli_fd
	int  cli_fd=-1;
	recv(fd,&cli_fd,4,0);
	cout<<fd<<"(sockpair[1])"<<"  Get Cli_fd"<<cli_fd<<endl<<endl;

	//将cli_fd加入到libevent
	
	struct event* cli_event = event_new(mthis->_base,cli_fd,EV_READ|EV_PERSIST,cli_cb,mthis);

	
	event_add(cli_event,NULL);

	mthis->_event_map.insert(pair<int,struct event *>(cli_fd,cli_event));
	
	int pth_num=mthis->_event_map.size();
	send(fd,&pth_num,4,0);
}


void* run(void *arg)
{
	cout<<"phread::run()"<<endl;
	Pmpthread mthis = (Pmpthread)arg;

	//为libevent申请空间
	mthis->_base = event_base_new();

	//将sock_1加入到libevent
	struct event* sock_1_event = event_new(mthis->_base,mthis->_sock_1,EV_READ|EV_PERSIST,sock_1_cb,mthis);

	if(NULL == sock_1_event)
	{
		cout<<"sock_1_event create fail"<<endl<<endl;
		exit(0);
	}
	
	event_add(sock_1_event,NULL);
	cout<<"sockpair[1] num:"<<mthis->_sock_1<<"  pthread dispatch start!"<<endl<<endl;
	event_base_dispatch(mthis->_base);
	cout<<"phread::run() end "<<endl<<endl;
}

mpthread::mpthread(int sock_1)
{
	 cout<<"mpthread()   ";
	_sock_1 = sock_1;
	cout<<"memary:"<<this<<"  sockpair[1]:"<<_sock_1<<endl;
	//启动子线程
	pthread_create(&pthread_id,NULL,run,this);
}







